package win.larryzeal.md;

/**
 * Created by 张少昆 on 2017/8/5.
 */
public class MyTry {
    public static void test(){
        byte b = -99;
        String x = Integer.toBinaryString(b);//int默认是4*8 =>32 bit

        System.out.println(x.substring(x.length() - 8));
    }
    //************************以下请忽略************************

    /**
     * bytes -> HEX String
     *
     * @param bytes
     * @return
     */
    public static String toHexString2(byte[] bytes){
        if(bytes == null){
            return null;
        }
        if(bytes.length == 0){
            return "00000000000000000000000000000000";
        }
        // 128/4 -> 32 len      ;注意顺序（大小端？）
        StringBuilder stringBuilder = new StringBuilder();
        for(int i = 0; i < bytes.length; i = i + 4){
            String fourBits2String = fourBits2String2(bytes, i, i + 4);
            Integer integer = Integer.valueOf(fourBits2String, 2);
            String hexString = Integer.toHexString(integer);
            stringBuilder.append(hexString);
        }
        return stringBuilder.toString();
    }

    /**
     * 不包含end。[start, end)
     *
     * @param bytes
     * @param start
     * @param end
     * @return
     */
    private static String fourBits2String2(byte[] bytes, int start, int end){
        StringBuilder stringBuilder = new StringBuilder();
        for(int i = start; i != end; i++){
            stringBuilder.append(bytes[i]);
        }

        return stringBuilder.toString();
    }

    public static String toHexString3(byte[] bytes){
        StringBuilder sb = new StringBuilder();
        for(int i = 0; i < bytes.length; i++){
            sb.append(Integer.toHexString(Integer.parseUnsignedInt(bytes[i] + "")));
        }
        return sb.toString();
    }
}
